console.log('Content Script: 抖音视频下载器已加载');

// 获取视频信息的主函数
function getVideoInfo() {
    console.log('Content Script: 开始获取视频信息');
    
    const videoInfo = {
        url: null,
        title: '抖音视频',
        timestamp: Date.now()
    };
    
    // 方法1: 从video元素获取
    const videos = document.querySelectorAll('video');
    console.log('Content Script: 找到video元素数量:', videos.length);
    
    for (const video of videos) {
        console.log('Content Script: 检查video元素:', {
            src: video.src,
            currentSrc: video.currentSrc,
            poster: video.poster,
            dataset: video.dataset
        });
        
        // 检查各种可能的视频源
        const possibleUrls = [
            video.src,
            video.currentSrc,
            video.getAttribute('data-src'),
            video.getAttribute('data-url'),
            video.getAttribute('src')
        ].filter(url => url && url.trim());
        
        for (const url of possibleUrls) {
            if (url && !url.startsWith('blob:') && !url.startsWith('data:')) {
                console.log('Content Script: 找到可能的视频URL:', url);
                videoInfo.url = url;
                break;
            }
        }
        
        if (videoInfo.url) break;
    }
    
    // 方法2: 从页面的全局变量中获取
    if (!videoInfo.url) {
        try {
            console.log('Content Script: 尝试从全局变量获取');
            
            // 检查常见的全局变量
            const globalVars = ['window.__INITIAL_STATE__', 'window.__NUXT__', 'window._SSR_HYDRATED_DATA'];
            
            for (const varName of globalVars) {
                try {
                    const data = eval(varName);
                    if (data) {
                        console.log('Content Script: 找到全局变量:', varName, data);
                        // 递归搜索视频URL
                        const foundUrl = searchForVideoUrl(data);
                        if (foundUrl) {
                            videoInfo.url = foundUrl;
                            console.log('Content Script: 从全局变量获取到URL:', foundUrl);
                            break;
                        }
                    }
                } catch (e) {
                    // 忽略错误，继续尝试下一个
                }
            }
        } catch (e) {
            console.log('Content Script: 全局变量获取失败:', e);
        }
    }
    
    // 方法3: 从页面脚本中提取
    if (!videoInfo.url) {
        try {
            console.log('Content Script: 尝试从script标签获取');
            const scripts = document.querySelectorAll('script');
            
            for (const script of scripts) {
                const content = script.textContent || script.innerHTML;
                if (!content) continue;
                
                // 查找视频URL模式
                        const urlPatterns = [
                            // 明确的视频文件
                            /https:\/\/[^"'\s]+\.mp4[^"'\s]*/g,
                            /https:\/\/[^"'\s]+\.m3u8[^"'\s]*/g,
                            /https:\/\/[^"'\s]+\.webm[^"'\s]*/g,
                            // 抖音相关域名的视频URL
                            /https:\/\/[^"'\s]*douyinvod[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
                            /https:\/\/[^"'\s]*bytedance[^"'\s]*\.com[^"'\s]*\/[^"'\s]*play[^"'\s]*/g,
                            /https:\/\/[^"'\s]*ixigua[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
                            /https:\/\/[^"'\s]*byteimg[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
                            /https:\/\/[^"'\s]*tos[^"'\s]*\.com[^"'\s]*\/[^"'\s]*video[^"'\s]*/g,
                            // API接口模式
                            /"video_url":\s*"([^"]+)"/g,
                            /"play_url":\s*"([^"]+)"/g,
                            /"playUrl":\s*"([^"]+)"/g,
                            /"play_addr":\s*"([^"]+)"/g,
                            // 包含video关键字但排除图片
                            /"src":\s*"([^"]+video[^"]*\.mp4[^"]*)"/g
                        ];
                
                for (const pattern of urlPatterns) {
                    const matches = content.match(pattern);
                    if (matches) {
                        for (const match of matches) {
                            let url = match;
                            // 提取引号内的URL
                            const quotedMatch = match.match(/"([^"]+)"/);
                            if (quotedMatch) {
                                url = quotedMatch[1];
                            }
                            
                            // 验证URL
                            if (url && url.startsWith('http') && !url.includes('.json') && 
                                !url.includes('.jpg') && !url.includes('.jpeg') && 
                                !url.includes('.png') && !url.includes('.gif') && 
                                !url.includes('.webp') && !url.includes('avatar') && 
                                !url.includes('cover')) {
                                console.log('Content Script: 从script标签找到URL:', url);
                                videoInfo.url = url;
                                break;
                            }
                        }
                        if (videoInfo.url) break;
                    }
                }
                if (videoInfo.url) break;
            }
        } catch (e) {
            console.log('Content Script: script标签解析失败:', e);
        }
    }
    
    // 方法4: 从网络请求中获取（通过performance API）
    if (!videoInfo.url) {
        try {
            console.log('Content Script: 尝试从网络请求获取');
            const resources = performance.getEntriesByType('resource');
            
            for (const resource of resources) {
                const url = resource.name;
                console.log('Content Script: 检查网络资源:', url);
                
                // 排除明确的非视频内容
                if (url && url.startsWith('http') && 
                    !url.includes('.json') && !url.includes('recommend') && 
                    !url.includes('feed') && !url.includes('.jpg') && 
                    !url.includes('.jpeg') && !url.includes('.png') && 
                    !url.includes('.gif') && !url.includes('.webp') && 
                    !url.includes('avatar') && !url.includes('cover') &&
                    !url.includes('comment') && !url.includes('user/info')) {
                    
                    // 检查是否可能是视频URL
                    if (url.includes('video') || url.includes('.mp4') || url.includes('.m3u8') ||
                        url.includes('douyinvod') || url.includes('ixigua') ||
                        url.includes('byteimg') || url.includes('tos') ||
                        url.includes('play_addr') || url.includes('aweme/v1/play') ||
                        url.includes('bytedance') || url.includes('snssdk') ||
                        /\/[a-zA-Z0-9_-]{15,}/.test(url)) { // 匹配长ID模式
                        console.log('Content Script: 从网络请求找到可能的视频URL:', url);
                        videoInfo.url = url;
                        break;
                    }
                }
            }
        } catch (e) {
            console.log('Content Script: 网络请求获取失败:', e);
        }
    }
    
    // 获取标题
    const titleSelectors = [
        '[data-e2e="video-desc"]',
        '.video-desc',
        'h1',
        '.title',
        '[data-e2e="browse-video-desc"]',
        '.browse-video-desc'
    ];
    
    for (const selector of titleSelectors) {
        const element = document.querySelector(selector);
        if (element && element.textContent.trim()) {
            videoInfo.title = element.textContent.trim().substring(0, 50);
            console.log('Content Script: 获取到标题:', videoInfo.title);
            break;
        }
    }
    
    console.log('Content Script: 最终视频信息:', videoInfo);
    return videoInfo;
}

// 递归搜索对象中的视频URL
function searchForVideoUrl(obj, depth = 0) {
    if (depth > 5 || !obj || typeof obj !== 'object') return null;
    
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            const value = obj[key];
            
            // 检查是否是视频URL
            if (typeof value === 'string' && value.startsWith('http')) {
                // 排除明确的非视频内容
                if (value.includes('.json') || value.includes('recommend') ||
                    value.includes('.jpg') || value.includes('.jpeg') || 
                    value.includes('.png') || value.includes('.gif') || 
                    value.includes('.webp') || value.includes('avatar') || 
                    value.includes('cover') || value.includes('comment') ||
                    value.includes('user/info') || value.includes('search/')) {
                    return null;
                }
                
                // 检查是否是可能的视频URL
                if (value.includes('video') || value.includes('.mp4') || value.includes('.m3u8') ||
                    value.includes('douyinvod') || value.includes('ixigua') ||
                    value.includes('byteimg') || value.includes('tos') ||
                    value.includes('play_addr') || value.includes('aweme/v1/play') ||
                    value.includes('bytedance') || value.includes('snssdk') ||
                    /\/[a-zA-Z0-9_-]{10,}\//.test(value)) { // 匹配长ID模式
                    return value;
                }
            }
            
            // 递归搜索
            if (typeof value === 'object') {
                const found = searchForVideoUrl(value, depth + 1);
                if (found) return found;
            }
        }
    }
    
    return null;
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('Content Script: 收到消息:', request);
    
    if (request.type === 'GET_VIDEO_INFO') {
        const videoInfo = getVideoInfo();
        console.log('Content Script: 返回视频信息:', videoInfo);
        sendResponse(videoInfo);
        return true;
    }
});

// 页面加载完成后尝试获取视频信息
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => {
        setTimeout(() => {
            console.log('Content Script: 页面加载完成，尝试获取视频信息');
            getVideoInfo();
        }, 2000);
    });
} else {
    setTimeout(() => {
        console.log('Content Script: 页面已加载，尝试获取视频信息');
        getVideoInfo();
    }, 1000);
}

console.log('Content Script: 抖音视频下载器 content script 初始化完成');